<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加用户按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="rolesDialog = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="roleslist" scripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
             
                <el-row :class="['bdbottom',i1===0 ? 'dbtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                  <!-- 一级权限 -->
                  <el-col :span="5" >
                    <el-tag closable @close="removeRightById(scope.row,item1.id)">
                      {{item1.authName}}
                    </el-tag>
                    <!-- el-icon-caret-right -->
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 二级三级权限 -->
                  <el-col :span="19">
                    <el-row :class="[i2===0 ? '' : 'dbtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                      <el-col :span="6">
                        <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                      </el-col>
                       <i class="el-icon-caret-right"></i>
                      <el-col :span="18">
                        <el-tag closable  type="warning" v-for="(item3) in item2.children" :key="item3.id"  @close="removeRightById(scope.row,item3.id)">
                            {{item3.authName}}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
           
          </template>  
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editFrom(scope.row.id)"
              >编辑</el-button
            >
            <el-button size="mini"
             type="danger"
             @click="RemoveRoles(scope.row.id)"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button size="mini"
           
             @click="showSetRightDialog(scope.row)"   type="warning" icon="el-icon-seting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="rolesDialog"
      width="60%"
      @close="addcoles"
    >
      <!-- 添加用户 -->
      <el-form ref="addFormaRef" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" ></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改用户 -->
      <el-dialog
      title="提示"
      :visible.sync="editDialog"
      width="60%"
      @close = 'editcolse'
    >
   
      <el-form ref="editFormaRef" :model="editForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" >
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoles()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
  title="提示"
  :visible.sync="setRightDialogVisible"
  width="30%"
  @close="Allroles"
  >
 <el-tree :data="roleForm"
  :props="RolesProps" show-checkbox
  node-key="id" default-expand-all
  :default-checked-keys = "Defkeys" ref="treeRef"
  ></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleslist: [],
      // 权限的对话框
      setRightDialogVisible:false,
      //添加角色对话框
      rolesDialog:false,
      // 编辑角色对话框
      editDialog:false,
      addForm:{
          roleName:"",
          roleDesc:""
      },
       editForm:{
      },
      roleForm:{

      },
      // 树形图的参数
      RolesProps:{
        children:'children',
        label:'authName'
      },
      // 获取展开数据的id
      roleId:'',
      //默认勾选项
      Defkeys:[],
      addFormRules:{
       roleName:[
          {required:true,message:'请输入角色名称',trigger:'blur'},
          {min:2,max:10,message:"字符必须在2-10之间",trigger:'blur'}
       ],
       roleDesc:[
         {required:true,message:'请输入角色简介',trigger:'blur'},
         {min:5,max:15,message:"字符必须在5-15之间",trigger:'blur'}
       ]

      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色信息失败')
      this.roleslist = res.data
      // console.log(this.roleslist)
    },
    addRoles(){
      this.$refs.addFormaRef.validate(async vali=>{
        if(!vali) return
        //发起网络请求
        const {data:res} =await this.$http.post('roles',this.addForm)
        if(res.meta.status!==201){
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getRoleList()
        this.rolesDialog = false
      })
    },
    //展示编辑表单的信息
   async editFrom(id){
      
      const{data:res} = await this.$http.get('roles/'+id)
      if(res.meta.status!==200){
        this.$message.error('查询失败')
      }
      this.editForm = res.data
      this.editDialog=true
       console.log(this.editForm)
    },
    //提交编辑信息
    editRoles(){
      this.$refs.editFormaRef.validate(async vali=>{
        if(!vali) return
        const{data:res} = await this.$http.put('roles/'+this.editForm.id,{
          roleDesc:this.editForm.roleDesc
        })

        if(res.meta.status !== 201){
          return this.$message.error('修改失败')
        }
        console.log(res.meta.status)
        this.getRoleList()
        this.editDialog = false
         this.$message.success('修改成功')
      })
    },
    editcolse(){
      this.$refs.editFormaRef.resetFields()
    },
    addcoles(){
      this.$refs.addFormaRef.resetFields()
    },
   async RemoveRoles(id){
       //  弹框询问用户是否删除数据
    const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        // 如果用户删除数据，则返回值为字符串 confirm
        // 如果用户取消，则返回值为字符串 cancel
    if(confirmResult != 'confirm')
    {
       this.$message({
            type: 'info',
            message: '已取消删除'
       });
    }else{
        const{data:res} = await this.$http.delete('roles/'+id)
        if(res.meta.status!==200){
          this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getRoleList()

    }
    },
   async removeRightById(role,rightId){
     const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
      if(confirmResult !== 'confirm')
      {
        return this.$message.info('以取消了删除')
      }
      //  `roles/${role.id}/rights/${rightId}`
      const{data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if(res.meta.status !== 200){
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      role.children = res.data
      
    },
    async showSetRightDialog(role){
      this.roleId = role.id
      this.setRightDialogVisible=true
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200){
        this.$message.error('获取权限列表失败')
      }
      this.roleForm = res.data
      this.getrefs(role,this.Defkeys)
    },
    // 通过递归的形式，获取角色下所有三级权限的id,
    //并保存到this.Defkeys中
    getrefs(node,arr){
      //如果当前 node 节点不包含children 属性，则是三级节点
      if(!node.children)
        return arr.push(node.id)
      node.children.forEach(item=>{
        this.getrefs(item,arr)
      })
    },
    //清空权限列表
    Allroles(){
      this.Defkeys=[]
    },
    async allotRights(){
      //获取半选中和全选中的ID
      // ...是把获取到的id全展开
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if(res.meta.status !==200)
        return this.$message.error('修改权限失败')
      this.$message.success('修改权限成功')
      this.getRoleList();
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.dbtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
 justify-items: center;
}
</style>
